import Database from 'better-sqlite3';
import path from 'path';

/**
 * 数据库核心模块
 * 只包含非业务逻辑的基础功能
 */
export class DatabaseCore {
  constructor(dbPath = 'network-firewall.db') {
    this.dbPath = path.resolve(dbPath);
    this.db = new Database(this.dbPath);
    this.initTables();
  }

  /**
   * 初始化数据库表结构
   */
  initTables() {
    // 创建请求表
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS requests (
        id TEXT PRIMARY KEY,
        url TEXT NOT NULL,
        method TEXT NOT NULL,
        headers TEXT,
        params TEXT,
        cookies TEXT,
        body TEXT,
        timestamp INTEGER,
        httpVersion TEXT,
        clientHttpVersion TEXT,
        remoteHttpVersion TEXT,
        tlsVersion TEXT,
        clientIp TEXT,
        remoteIp TEXT
      )
    `);

    // 创建响应表
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS responses (
        id TEXT PRIMARY KEY,
        requestId TEXT NOT NULL,
        statusCode INTEGER,
        headers TEXT,
        cookies TEXT,
        body TEXT,
        bodySize INTEGER,
        timestamp INTEGER,
        httpVersion TEXT,
        remoteHttpVersion TEXT,
        tlsVersion TEXT,
        FOREIGN KEY (requestId) REFERENCES requests (id)
      )
    `);

    // 创建事务表
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS transactions (
        id TEXT PRIMARY KEY,
        requestId TEXT NOT NULL,
        responseId TEXT,
        duration INTEGER,
        createdAt INTEGER,
        FOREIGN KEY (requestId) REFERENCES requests (id),
        FOREIGN KEY (responseId) REFERENCES responses (id)
      )
    `);

    // 创建规则表
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS rules (
        id TEXT PRIMARY KEY,
        name TEXT NOT NULL,
        description TEXT,
        enabled INTEGER DEFAULT 1,
        conditions TEXT,
        actions TEXT,
        createdAt INTEGER,
        updatedAt INTEGER
      )
    `);

    // 创建索引
    this.createIndexes();

    console.log('📚 数据库表结构初始化完成');
  }

  /**
   * 创建数据库索引
   */
  createIndexes() {
    this.db.exec(`
      CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests (timestamp);
      CREATE INDEX IF NOT EXISTS idx_requests_url ON requests (url);
      CREATE INDEX IF NOT EXISTS idx_requests_method ON requests (method);
      CREATE INDEX IF NOT EXISTS idx_transactions_createdAt ON transactions (createdAt);
      CREATE INDEX IF NOT EXISTS idx_responses_requestId ON responses (requestId);
      CREATE INDEX IF NOT EXISTS idx_rules_enabled ON rules (enabled);
    `);
  }

  /**
   * 执行SQL查询
   */
  prepare(sql) {
    return this.db.prepare(sql);
  }

  /**
   * 执行SQL语句
   */
  exec(sql) {
    return this.db.exec(sql);
  }

  /**
   * 开始事务
   */
  transaction(fn) {
    return this.db.transaction(fn);
  }

  /**
   * 获取数据库信息
   */
  getInfo() {
    const info = this.db.prepare("PRAGMA database_list").all();
    const userVersion = this.db.prepare("PRAGMA user_version").get();
    const pageCount = this.db.prepare("PRAGMA page_count").get();
    const pageSize = this.db.prepare("PRAGMA page_size").get();
    
    return {
      path: this.dbPath,
      version: userVersion.user_version,
      pageCount: pageCount.page_count,
      pageSize: pageSize.page_size,
      size: pageCount.page_count * pageSize.page_size,
      databases: info
    };
  }

  /**
   * 获取表信息
   */
  getTableInfo(tableName) {
    try {
      const columns = this.db.prepare(`PRAGMA table_info(${tableName})`).all();
      const indexes = this.db.prepare(`PRAGMA index_list(${tableName})`).all();
      const count = this.db.prepare(`SELECT COUNT(*) as count FROM ${tableName}`).get();
      
      return {
        name: tableName,
        columns: columns,
        indexes: indexes,
        rowCount: count.count
      };
    } catch (error) {
      return null;
    }
  }

  /**
   * 获取所有表
   */
  getAllTables() {
    const tables = this.db.prepare(`
      SELECT name FROM sqlite_master 
      WHERE type='table' AND name NOT LIKE 'sqlite_%'
    `).all();
    
    return tables.map(table => this.getTableInfo(table.name)).filter(Boolean);
  }

  /**
   * 清空指定表
   */
  clearTable(tableName) {
    return this.db.prepare(`DELETE FROM ${tableName}`).run();
  }

  /**
   * 清空所有表
   */
  clearAllTables() {
    const transaction = this.db.transaction(() => {
      this.db.exec('DELETE FROM transactions');
      this.db.exec('DELETE FROM responses');
      this.db.exec('DELETE FROM requests');
      this.db.exec('DELETE FROM rules');
    });
    
    return transaction();
  }

  /**
   * 执行真空操作（压缩数据库）
   */
  vacuum() {
    return this.db.exec('VACUUM');
  }

  /**
   * 分析数据库（更新统计信息）
   */
  analyze() {
    return this.db.exec('ANALYZE');
  }

  /**
   * 检查数据库完整性
   */
  checkIntegrity() {
    const result = this.db.prepare('PRAGMA integrity_check').all();
    return result.length === 1 && result[0].integrity_check === 'ok';
  }

  /**
   * 获取数据库统计信息
   */
  getStats() {
    const stats = {};
    
    try {
      // 获取各表的行数
      const tables = ['requests', 'responses', 'transactions', 'rules'];
      for (const table of tables) {
        const result = this.db.prepare(`SELECT COUNT(*) as count FROM ${table}`).get();
        stats[table] = result.count;
      }
      
      // 获取数据库大小信息
      const dbInfo = this.getInfo();
      stats.databaseSize = dbInfo.size;
      stats.pageCount = dbInfo.pageCount;
      stats.pageSize = dbInfo.pageSize;
      
    } catch (error) {
      console.error('❌ 获取数据库统计信息失败:', error.message);
    }
    
    return stats;
  }

  /**
   * 关闭数据库连接
   */
  close() {
    if (this.db) {
      this.db.close();
      console.log('📚 数据库连接已关闭');
    }
  }

  /**
   * 获取原始数据库实例（谨慎使用）
   */
  getRawDatabase() {
    return this.db;
  }
} 